package com.GoodModsLab.Azalea2

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.wear.compose.material.ExperimentalWearMaterialApi
import androidx.wear.compose.material.rememberSwipeableState
import androidx.wear.compose.material.swipeable
import com.GoodModsLab.Azalea2.Utils.ConfigUtils
import com.GoodModsLab.Azalea2.ui.theme.Azalea2Theme
import com.GoodModsLab.Azalea2.ui.theme.Pink80
import com.GoodModsLab.Azalea2.ui.theme.card_background
import com.GoodModsLab.Azalea2.ui.theme.card_muted_text
import com.GoodModsLab.Azalea2.ui.theme.card_normal
import com.GoodModsLab.Azalea2.ui.theme.neutral_color_black
import com.GoodModsLab.Azalea2.ui.theme.neutral_color_red
import com.GoodModsLab.Azalea2.ui.theme.neutral_color_white

class MainActivity : ComponentActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Azalea2Theme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {

                    val navController = rememberNavController()

                    NavHost(navController = navController, startDestination = "menuScreen") {
                        composable("menuScreen") {
                            MenuScreen(navController = navController)
                        }
                        composable(
                            route = "gameScreen/{mode}"
                        ) { navBackStackEntry ->
                            GameScreen(navController = navController,
                                mode_game = navBackStackEntry.arguments?.getString("mode", "") ?: "")
                        }
                    }

                }
            }
        }
    }

    @Composable
    fun MenuScreen(navController: NavController) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .paint(
                    painterResource(id = R.drawable.ic_smoth_background),
                    contentScale = ContentScale.FillBounds
                )
        ) {
            Image(
                painter = painterResource(id = R.drawable.ic_title_game),
                contentDescription = null,
                modifier = Modifier
                    .align(Alignment.Center)
            )

            Text(
                text = "Версия: " + ConfigUtils().getAppVersion(applicationContext),
                style = TextStyle(color = card_muted_text),
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(8.dp)
            )


            Row(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .padding(bottom = 16.dp)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.weight(1f)
                ) {
                    Button(onClick = { navController.navigate("gameScreen/script") }, modifier = Modifier.padding(5.dp)) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_magic_book),
                                contentDescription = null,
                                modifier = Modifier.size(40.dp)
                            )
                            Text(
                                text = "Сценарий",
                                style = TextStyle(color = Color.White),
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }

                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.weight(1f)
                ) {
                    Button(onClick = { navController.navigate("gameScreen/survival") }, modifier = Modifier.padding(5.dp)) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_health_),
                                contentDescription = null,
                                modifier = Modifier.size(40.dp)
                            )
                            Text(
                                text = "Выживание",
                                style = TextStyle(color = Color.White),
                                textAlign = TextAlign.Center
                            ) 
                        }

                    }
                }

                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.weight(1f)
                ) {
                    Button(onClick = { Toast.makeText(applicationContext, "Скоро...", Toast.LENGTH_LONG).show() }, modifier = Modifier.padding(5.dp)) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_wing),
                                contentDescription = null,
                                modifier = Modifier.size(40.dp)
                            )
                            Text(
                                text = "Онлайн",
                                style = TextStyle(color = Color.White),
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }

            }

        }

    }
    

    @Composable
    fun GameScreen(navController: NavController, mode_game: String) {
        var showDialog by remember { mutableStateOf(true) }
        var image_info_dialog by remember { mutableIntStateOf(R.drawable.ic_apple) }
        var title_info_dialog by remember { mutableStateOf("") }
        var text_info_dialog by remember { mutableStateOf("") }

        image_info_dialog = R.drawable.ic_mob_0_nobackground
        title_info_dialog = "Секретарь Раяна Гослинга"
        text_info_dialog = "С Возращением в Азалию! Хорошие новости, мафии в стране нет, но появились другие проблемы... Нам нужна ваша помощь!\nЧтобы отвечать на запросы жителей нужно смахивать карточки в соответствующие стороны." +
                "\nВверху указаны характеристики вашей страны, если что, то их можно также смахивать для просмотра в разные стороны, либо нажать для дополнительной информации.\nНадеюсь это поможет вам, успехов!"


        if (showDialog) {
            Dialog(onDismissRequest = { showDialog = false }) {
                Surface(
                    shape = RoundedCornerShape(28.dp),
                    color = card_normal
                ) {
                    Column(
                        modifier = Modifier
                            .padding(16.dp)
                            .fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = image_info_dialog),
                            contentDescription = null,
                            modifier = Modifier.size(130.dp)
                        )
                        Text(
                            text = title_info_dialog,
                            style = TextStyle(color = neutral_color_red, fontSize = 24.sp),
                            textAlign = TextAlign.Center
                        )
                        Text(
                            text = text_info_dialog,
                            style = TextStyle(color = neutral_color_white, fontSize = 16.sp),
                            textAlign = TextAlign.Start
                        )
                        Button(
                            onClick = {showDialog = false},
                            modifier = Modifier.padding(top = 16.dp)
                        ) {
                            Text("Понятно. За работу!")
                        }
                    }
                }
            }
        }

        Column(Modifier.fillMaxSize()) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(card_background)
                    .height(IntrinsicSize.Min)
            ) {
                CustomToolbar()
            }

            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxSize()
                    .padding(0.dp)
                    .background(card_background)
            ) {
                MainContent(mode_game)
            }

            Box(
                modifier = Modifier
                    .height(IntrinsicSize.Min)
                    .fillMaxWidth()
                    .background(Color.Green)
            ) {
                CustomBottomNavigationBar(onStartClick = {Toast.makeText(applicationContext, "Скоро...", Toast.LENGTH_LONG).show()}, onLawsClick = {Toast.makeText(applicationContext, "Скоро...", Toast.LENGTH_LONG).show()} )
            }
        }

    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun CustomToolbar() {
        var showDialog by remember { mutableStateOf(false) }
        var image_info_dialog by remember { mutableIntStateOf(R.drawable.ic_apple) }
        var title_info_dialog by remember { mutableStateOf("") }
        var text_info_dialog by remember { mutableStateOf("") }
        val scrollState = rememberScrollState()

       if (showDialog) {
            Dialog(onDismissRequest = { showDialog = false }) {
                Surface(
                    shape = RoundedCornerShape(28.dp),
                    color = card_normal
                ) {
                    Column(
                        modifier = Modifier
                            .padding(16.dp)
                            .fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = image_info_dialog),
                            contentDescription = null,
                            modifier = Modifier.size(100.dp)
                        )
                        Text(
                            text = title_info_dialog,
                            style = TextStyle(color = neutral_color_red, fontSize = 24.sp),
                            textAlign = TextAlign.Center
                        )
                        Text(
                            text = text_info_dialog,
                            style = TextStyle(color = neutral_color_white, fontSize = 16.sp),
                            textAlign = TextAlign.Start
                        )
                        Button(
                            onClick = {showDialog = false},
                            modifier = Modifier.padding(top = 16.dp)
                        ) {
                            Text("Понятно")
                        }
                    }
                }
            }
        }

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(IntrinsicSize.Min)
                .padding(0.dp)
                .horizontalScroll(scrollState),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Ecology
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                        showDialog = true
                        image_info_dialog = R.drawable.ic_apple
                        title_info_dialog = "Экология"
                        text_info_dialog = "Здесь показывается экология вашей страны. На экологию действуют различные научные или военные действия" }, modifier = Modifier.padding(5.dp)) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_apple),
                            contentDescription = null,
                            modifier = Modifier.size(50.dp)
                        )
                        Text(
                            text = "100%",
                            style = TextStyle(color = Color.White),
                            textAlign = TextAlign.Center
                        )
                    }

                }
            }

            // Believers
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                    showDialog = true
                    image_info_dialog = R.drawable.ic_buff
                    title_info_dialog = "Вера"
                    text_info_dialog = "Вера - это двигатель вашей общественности. Вера влияет на доверие к вам, чем ниже оно - тем меньше вам доверяют. Учитываются общественные и социальные процессы"  }, modifier = Modifier.padding(5.dp)) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_buff),
                            contentDescription = null,
                            modifier = Modifier.size(50.dp)
                        )
                        Text(
                            text = "100%",
                            style = TextStyle(color = Color.White),
                            textAlign = TextAlign.Center
                        )
                    }

                }
            }

            // Shield
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                    showDialog = true
                    image_info_dialog = R.drawable.ic_block_shield
                    title_info_dialog = "Вооружение"
                    text_info_dialog = "Оборона вашей страны зависит от науки и испытаний. Учтите, что вооружение может затрагивать многие аспекты вашей страны" }, modifier = Modifier.padding(5.dp)) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_block_shield),
                            contentDescription = null,
                            modifier = Modifier.size(50.dp)
                        )
                        Text(
                            text = "100%",
                            style = TextStyle(color = Color.White),
                            textAlign = TextAlign.Center
                        )
                    }

                }
            }

            // Money
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                    showDialog = true
                    image_info_dialog = R.drawable.ic_gold_ingot
                    title_info_dialog = "Бюджет"
                    text_info_dialog = "Деньги - это инструмент экономики. У кого деньги, у того и власть?..."  }, modifier = Modifier.padding(5.dp)) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_gold_ingot),
                            contentDescription = null,
                            modifier = Modifier.size(50.dp)
                        )
                        Text(
                            text = "100%",
                            style = TextStyle(color = Color.White),
                            textAlign = TextAlign.Center
                        )
                    }

                }
            }

            // Gems
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Button(onClick = {
                    showDialog = true
                    image_info_dialog = R.drawable.ic_water_crystal
                    title_info_dialog = "Кристаллы"
                    text_info_dialog = "Кристаллы - это новая валюта, которую принимает ваша канцелярия. Вы можете заплатить ей несколько кристаллов для создания закона в вашей стране. Вы можете управлять страной также и законами - они оказывают большее влияние и без ущерба" }, modifier = Modifier.padding(0.dp)) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.ic_water_crystal),
                            contentDescription = null,
                            modifier = Modifier.size(50.dp)
                        )
                        Text(
                            text = "100",
                            style = TextStyle(color = Color.White),
                            textAlign = TextAlign.Center
                        )
                    }

                }
            }

        }

    }

    @Composable
    fun MainContent(mode_game: String) {
        var swipeDirection by remember { mutableStateOf("") }

        Image(
            painter = painterResource(id = R.drawable.ic_mob_1),
            contentDescription = null,
            modifier = Modifier
                .fillMaxSize()
                .padding(0.dp)
                .pointerInput(Unit) {
                    detectDragGestures { _, dragAmount ->
                        if (dragAmount.x > 15) {
                            swipeDirection = "Swiped right"
                        } else if (dragAmount.x < 15) {
                            swipeDirection = "Swiped left"
                        }
                    }
                }
        )

        if (swipeDirection.isNotEmpty()) {
            Text(
                text = swipeDirection,
                color = Color.White,
                // modifier = Modifier.align(Alignment.TopCenter)
            )
        }

//        Box(
//            modifier = Modifier
//                .fillMaxSize()
//                .padding(0.dp)
//                .pointerInput(Unit) {
//                    detectDragGestures { _, dragAmount ->
//                        if (dragAmount.x > 15) {
//                            swipeDirection = "Swiped right"
//                        } else if (dragAmount.x < 15) {
//                            swipeDirection = "Swiped left"
//                        }
//                    }
//                }
//        ) {
//            Image(
//                painter = painterResource(id = R.drawable.ic_mob_1),
//                contentDescription = null,
//                modifier = Modifier
//                    .fillMaxSize()
//                    // .size(300.dp, 533.dp)
//                    .align(Alignment.Center)
//            )
//
//            if (swipeDirection.isNotEmpty()) {
//                Text(
//                    text = swipeDirection,
//                    color = Color.White,
//                    modifier = Modifier.align(Alignment.TopCenter)
//                )
//            }
//        }
    }

    @Composable
    fun CustomBottomNavigationBar(onStartClick: () -> Unit, onLawsClick: () -> Unit) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(0.dp),
            verticalArrangement = Arrangement.Bottom
        ) {
            BottomAppBar(
                containerColor = card_background,
                modifier = Modifier
                    .background(card_background)
                    .fillMaxWidth()
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.Bottom
                ) {
                    BottomNavigationItem(
                        text = "Главная",
                        icon = painterResource(id = R.drawable.ic_stone_door),
                        onClick = onStartClick
                    )
                    BottomNavigationItem(
                        text = "Законы",
                        icon = painterResource(id = R.drawable.ic_parchment),
                        onClick = onLawsClick
                    )
                }
            }
        }
    }


    @Composable
    fun BottomNavigationItem(text: String, icon: Painter, onClick: () -> Unit) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Bottom
        ) {
            IconButton(onClick = onClick, modifier = Modifier.size(50.dp)) {
                Image(painter = icon, contentDescription = null)
            }
            Text(
                text = text,
                style = TextStyle(color = Color.White),
                textAlign = TextAlign.Center
            )
        }
    }

    @Preview
    @Composable
    fun PreviewMenuScreen() {
        MenuScreen(navController = rememberNavController())
    }

    @Preview
    @Composable
    fun PreviewGameScreen() {
        GameScreen(navController = rememberNavController(), mode_game = "survival")
    }

}